const express = require('express')
const fs = require('fs')
const config = require(process.cwd() + '/src/config/config')
const fileUtils = require(process.cwd() + '/src/utils/file')

let router = express.Router()

/* GET users listing. */
router.post('/', function(req, res) {
  // 图集的名称
  const tileset = req.body.tileset
  // 图集单元的宽度
  const itemWidth = req.body.width
  // 图集单元的高度
  const itemHeight = req.body.height
  // 图集一行有多少单元
  const colNum = req.body.colNum
  
  // 创建空白图集
  let setting = {
    name: tileset,
    colNum: colNum,
    itemWidth: itemWidth,
    itemHeight: itemHeight,
    list: []
  }
  // 保存settings
  const settingPath = config.tilesetsPath + tileset + '.json'
  const buffer = JSON.stringify(setting)
  const imagePath = config.imagesPath + tileset
  
  // 先创建分类资源文件夹
  fileUtils.createFolder(imagePath).then(() => {
    return fs.promises.writeFile(settingPath, buffer)
  })
  // 再保存配置文件
  .then(() => {
    res.sendStatus(200)
  })
  .catch((err) => {
    console.log(err)
    res.sendStatus(500)
  })
})

module.exports = router
